package com.linxs.topcham.intefaces.controller.admin;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Ints;
import com.kissme.core.orm.Page;
import com.linxs.topcham.application.fnas.FansService;
import com.linxs.topcham.application.fnas.KdtapiService;
import com.linxs.topcham.application.org.AgencyOrgService;
import com.linxs.topcham.application.task.OrderService;
import com.linxs.topcham.domain.fans.Fans;
import com.linxs.topcham.domain.fans.Order;
import com.linxs.topcham.domain.kdtapi.KdtFans;
import com.linxs.topcham.domain.org.AgencyOrg;
import com.linxs.topcham.domain.user.User;

@Controller
@RequestMapping(value = "/admin")
public class KdtApiController {
	
	private Logger log = LoggerFactory.getLogger(KdtApiController.class);

	@Autowired
	private FansService fansService;

	@Autowired
	private AgencyOrgService orgService;

	@Autowired
	private KdtapiService apiserService;
	
	@Autowired
	private OrderService orderService;

	@RequestMapping(value = "/refreshdata", method = RequestMethod.POST)
	@ResponseBody
	public String refreshData() {
		try {

			log.info("管理员执行口袋通粉丝同步任务"); 
			
//			apiserService.deleteApiFansData();
			for (Fans fans : apiserService.query()) {
				
				if(apiserService.isExist(fans.getWeixinOpenId()))	{
					continue;
				}
				
				KdtFans kdtFans = new KdtFans();
				kdtFans.setAvatar(fans.getAvatar());
				kdtFans.setCity(fans.getCity());
				kdtFans.setFollowTime(fans.getFollowTime());
				kdtFans.setNick(fans.getNick());
				kdtFans.setProvince(fans.getProvince());
				kdtFans.setSex(fans.getSex());
				kdtFans.setUserId(fans.getUserId());
				kdtFans.setWeixinOpenId(fans.getWeixinOpenId());
				kdtFans.setTags(fans.getTags());
				try {

					apiserService.save(kdtFans);
				} catch (Exception e) {
					kdtFans.setNick(new String(kdtFans.getNick().getBytes(), "GBK"));
					apiserService.save(kdtFans);
				}
			}
			
			log.info("管理员执行口袋通粉丝同步任务同步成功！"); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	@RequestMapping(value = "/salesCommissions", method = RequestMethod.GET)
	public String salesCommissions(Model model, HttpServletRequest request) {
		try {

			String username = ((User) request.getSession().getAttribute("user")).getUsername();
			AgencyOrg org = orgService.getByAccount(username);
			List<Fans> fanss = fansService.queryMyFans(org.getAccount());

//			List<Order> orders = apiserService.queryThisMonthOrders(org.getAreas(), "TRADE_BUYER_SIGNED");
			List<Order> orders = orderService.queryFinishOrderOfOrg(org.getId());
			
			for(Order order : orders) {
				if (null != org) {
					if (order.getAddress().indexOf(org.getAreas()) != -1 || "全国地区".equals(org.getAreas())) {
						order.setBase("0.05");
						order.setCommission(new BigDecimal("0.05").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
								.setScale(2, BigDecimal.ROUND_DOWN));
					} else {
						order.setBase("0.03");
						order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
								.setScale(2, BigDecimal.ROUND_DOWN));
					}
					order.setOrgId(org.getId());
				} else {
					order.setBase("0.03");
					order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
							.setScale(2, BigDecimal.ROUND_DOWN));

				}
			}
			
			
			
			
			
			
			List<Order> result = Lists.newArrayList();

			for (Fans fans : fanss) {
				for (Order order : orders) {
					if(fans.getUserId().equals(order.getWeixinUserId())) {
						result.add(order);
					}
				}
			}

			model.addAttribute("result", result);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "/kdtapi/salesCommissions";
	}

	@RequestMapping(value = "/salesCommissions/{username}", method = RequestMethod.GET)
	@ResponseBody
	public String salesCommissions(Model model, @PathVariable("username") String username) {

		AgencyOrg org = orgService.getByAccount(username);
//		List<Fans> fanss = fansService.queryMyFans(org.getAccount());

//		List<Order> orders = apiserService.queryThisMonthOrders(org.getAreas(), "TRADE_BUYER_SIGNED");
		List<Order> orders = orderService.queryFinishOrderOfOrg(org.getId());
		
		for(Order order : orders) {
			if (null != org) {
				if (order.getAddress().indexOf(org.getAreas()) != -1 || "全国地区".equals(org.getAreas())) {
					order.setBase("0.05");
					order.setCommission(new BigDecimal("0.05").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
							.setScale(2, BigDecimal.ROUND_DOWN));
				} else {
					order.setBase("0.03");
					order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
							.setScale(2, BigDecimal.ROUND_DOWN));
				}
				order.setOrgId(org.getId());
			} else {
				order.setBase("0.03");
				order.setCommission(new BigDecimal("0.03").setScale(2, BigDecimal.ROUND_DOWN).multiply(order.getPayment())
						.setScale(2, BigDecimal.ROUND_DOWN));

			}
		}
		
		
		BigDecimal commissions = new BigDecimal("0.0").setScale(2, BigDecimal.ROUND_DOWN);
		for(Order o : orders) {
			commissions = commissions.add(o.getCommission());
		}
		return commissions.toString();
		
		
		
//		BigDecimal commissions = new BigDecimal("0.0").setScale(2, BigDecimal.ROUND_DOWN);
//		for (Fans fans : fanss) {
//			for (Order order : orders) {
//				if(fans.getUserId().equals(order.getWeixinUserId())) {
//					commissions = commissions.add(order.getCommission());
//				}
//			}
//		}
//
//		return String.valueOf(commissions.setScale(2, BigDecimal.ROUND_DOWN).doubleValue());
	}

	@RequestMapping(value = "/kdtapi", method = RequestMethod.GET)
	public String list(Model model, HttpServletRequest request) {
		try {

			Page<KdtFans> page = new Page<KdtFans>();
			int pageNo = WebUtils.getCleanParam(request, "pageNo") == null ? 0 : Ints.tryParse(WebUtils.getCleanParam(request, "pageNo"));
			String nick = WebUtils.getCleanParam(request, "nick") == null ? "" : WebUtils.getCleanParam(request, "nick");
			page.setPageNo(pageNo);

			if (!Strings.isNullOrEmpty(nick)) {
				nick = URLDecoder.decode(nick, "UTF-8");
				Map<String, Object> params = Maps.newHashMap();
				params.put("nick", "%" + nick + "%");
				page.setParams(params);
				model.addAttribute("nick", nick);
			}
			model.addAttribute("page", apiserService.query(page));
			model.addAttribute("orgs", orgService.query());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "/kdtapi/list";
	}

	@RequestMapping(value = "/kdtapi/relieve", method = RequestMethod.POST)
	@ResponseBody
	public String relieve(@RequestParam("id") String id) {
		fansService.relieve(id);
		return "success";
	}

	@RequestMapping(value = "/kdtapi/relevance")
	@ResponseBody
	public String relevanceFans(Model model, HttpServletRequest request) {
		String orgId = request.getParameter("orgId");

		Iterable<String> fansCollection = Splitter.on("[;]").split(request.getParameter("fansCollection"));

		for (String item : fansCollection) {

			String[] items = item.split("\\[-\\]");

			String weixinOpenId = items[0];
			String followTime = items[1];
			String sex = items[2];
			String nick = items[3];
			String province = items[4];
			String userId = items[5];
			String avatar = items[6];
			String city = items.length > 7 ? items[7] : "";

			Fans fans = new Fans();
			fans.setAvatar(avatar).setCity(city).setFollowTime(followTime).setNick(nick).setOrg(orgService.loadAgencyOrgInfo(Long.valueOf(orgId)))
					.setProvince(province).setSex(sex).setUserId(userId).setWeixinOpenId(weixinOpenId);

			fansService.relevanceFansToOrg(fans);
		}

		return "success";
	}

}
